<?php
class PaymentController extends FrontendController
{
	public function actionIndex()
	{
		if(Yii::app()->user->isGuest){
			Yii::app()->user->setFlash('login-msg','Bạn phải đăng nhập để sử dụng tính năng này.');
			$this->redirect('/user/login');
			Yii::app()->end();
		}
		
		$orderForm = new OrderForm;
		if(isset($_POST['OrderForm'])){
			$orderForm->attributes = $_POST['OrderForm'];
			$cart = Shop::getCartContent();
			$data = array();
			foreach ($cart as $key => $value){
				$product = Products::model()->findByPk($value['product_id']);
				$data[$key]= $value;
				$data[$key]['price'] = $product->getPrice();
				$data[$key]['price_total'] = $data[$key]['price']*$value['amount'];
			}
			
			if($orderForm->validate()){
				$model = new FrontendShopOrderTransactionModel;
				$model->user_id 		= Yii::app()->user->id;
				$model->username 		= $orderForm->name;
				$model->phone			= $orderForm->phone;
				$model->ship_address	= $orderForm->address;
				$model->ship_method 	= $orderForm->shipMethod;
				$model->payment_method 	= $orderForm->methodPayment;
				$model->cart			= CJSON::encode($data);
				$model->status			= 3;
				$model->created_datetime= date('Y-m-d H:i:s');
				if($model->save()){
					Yii::app()->user->setFlash('order-shop-completed', Yii::t('shop', 'We will check your order and shipping for you.'));
					$this->redirect(array('/payment/completed'));
				}
				//
			}
		}
		$this->render('index', array(
					'orderForm'=>$orderForm
				));
	}
	public function actionCompleted()
	{
		$this->render('completed');
	}
}